import $ from "jquery";
let Utility = {
  throttle: (fn, delay) => {
    let last = 0;
    return function() {
      const now = Date.now();
      if (now - last > delay) {
        last = now;
        fn.call(this, ...arguments);
      }
    };
  },
  debounce: (fn, delay) => {
    let timer = null;
    return function() {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, delay);
    };
  },

  getSearchParams: function() {
    let args = {};
    let query = location.search.substring(1);
    let pairs = query.split("&");
    for (let i = 0; i < pairs.length; i++) {
      let pos = pairs[i].indexOf("=");
      if (pos == -1) {
        continue;
      }
      let name = pairs[i].substring(0, pos);
      let value = pairs[i].substring(pos + 1);
      value = decodeURIComponent(value);
      args[name] = value;
    }
    return args;
  },

  downloadFile: (fileurl, filename) => {
    let a = document.createElement("a");
    a.download = filename; // 下载后文件名
    a.style.display = "none";
    $.ajax({
      url: fileurl,
      xhrFields: { responseType: "arraybuffer" },
    }).done(result => {
      let blob = new Blob([result]); // 字符内容转变成blob地址 二进制地址
      a.href = URL.createObjectURL(blob);
      document.body.appendChild(a);
      a.click(); // 触发点击
      document.body.removeChild(a); // 然后移除
    });
  },
  imgPreLoad: function(url, id) {
    if (!url) return;
    return new Promise(resolve => {
      const img = new Image();
      img.src = url;
      img.onload = function() {
        img.width = "0";
        img.height = "0";
        img.style.display = "none";
        img.id = id;
        document.body.appendChild(img);
        resolve();
      };
    });
  },
};
export default Utility;
